<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * Copyright (C) 2007  Robert Moss
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

/**
   * displays match results in a table...
   *
   * @param object $matches
   * @param array objects $ResultTeams teams info
   * @param array $config
   */
  function show_matches( &$matchesInfo, &$ResultTeams, &$config ) {
    global $joomleague, $database;
    
    $division = mosGetParam($_REQUEST, 'division', 0);
    
    $favteams=explode(",", $joomleague->fav_team);
    $k=0;
    //$ResultTeams = $joomleague->getTeamsIndexedById(null, $division);    
    
    if ($config['show_dnp_teams'] == 1) 
    {
      $teams_in_league=array();
      foreach ($ResultTeams AS $Ateam) 
      { 
        if ($Ateam->division_id==$division || $Ateam->parent_division_id==$division) {
          $teams_in_league[]=$Ateam;
        }
      }
    }
    
    $olddate = '';
    $playing_teams = array();
    
    foreach($matchesInfo as $matchInfo) 
    {
      $config['class'] = ($k == 0)? $config['style_class1'] : $config['style_class2'];
      
      if ($config['show_dnp_teams'] == 1) {
        HTML_joomleague::addPlayingTeams($playing_teams, $matchInfo->matchpart1, $matchInfo->matchpart2);
      }
      HTML_joomleague::newDayHeading($matchInfo->match_date, $olddate, $config);

      show_match_row( $matchInfo, $ResultTeams, $favteams, $config );
      $k = 1 - $k;
    }
    
    if ($config['show_dnp_teams'] == 1) 
    {
      echo '<tr><td colspan="'.$config['colspan'].'"><div style="text-align:center">';
      HTML_joomleague::show_not_playing_teams($playing_teams, $teams_in_league, $config);
      echo '</div></td></tr>';
    }
  }
  
  /**
	 * display a row in match results table
	 *
	 * @param object $matchInfo
	 * @param object $teamsInfo
	 * @param array $favteam
	 * @param array $config
	 */
	function show_match_row( &$matchInfo, &$teamsInfo, &$favteam, &$config ) {
	  global $joomleague, $database;
	  
	  $divLevel = intval(mosGetParam($_REQUEST, 'division', 0));
	  $hometeam = $teamsInfo[$matchInfo->matchpart1];
	  $guestteam = $teamsInfo[$matchInfo->matchpart2];
	  ?>
	  <tr class="<?php echo $config['class'];?>">
	  <?php
	  if ($config['show_match_number']==1) {
	    ?>
	    <td align="left" nowrap="nowrap" valign="top"><?php
	    echo $matchInfo->match_number;?>&nbsp;</td>
	    <?php
	  }
	  if ($config['show_events']==1) {
	    ?>
	    <td align="left" nowrap="nowrap" valign="top"><?php
	    $are_there_events = $joomleague->areThereEvents ($matchInfo->match_id);
	    if ($are_there_events > 0 || $matchInfo->match_result_detail!="") {
	      ?> <a href="javascript:void(0);"
	      onclick="switchMenu('info<?php echo $matchInfo->match_id;?>');return false;"
	      title="<?php
	             echo _JL_SHOW_INFO;?>"> <img
	      src="<?php echo _JOOMLA_JL_LIVE_SITE;?>/administrator/components/com_joomleague/images/events.png"
	      alt="<?php
	             echo _JL_SHOW_INFO;?>"
	      title="<?php echo _JL_SHOW_INFO;?>" border="0" /></a> <?php
	    }
	    ?></td>
	    <?php
	  }
	  if ($joomleague->project_type=='DIVISIONS_LEAGUE' && isset($config['show_division']) && $config['show_division']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top" style="text-align: center"><?php
	    if (isset($config['results_below']) && $config['results_below']==1) {
	      $config['spacer'] = '<br />';
	    }
	    echo HTML_joomleague::showDivisonRemark($hometeam, $guestteam, $config);
	    ?></td>
	    <?php
	  }
	  if ($config['show_playground']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top" style="text-align: center"><?php
	    HTML_joomleague::showPlayground($hometeam, $guestteam, $matchInfo, $config['show_playground_alert']);
	    ?></td>
	    <?php
	  }
	  if ($config['show_time']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top"><?php
	    echo HTML_joomleague::format_match_time($matchInfo, $joomleague, $config);
	    ?></td>
	    <?php
	  }
	  if (isset($config['results_below']) && $config['results_below']==1){
		  if ($config['show_logo_small'] > 0) {
		    ?>
		    <td align="center" valign="top" nowrap="nowrap" style="width: 5%;"><?php
		    HTML_joomleague::showClubIcon($hometeam, $config['show_logo_small'], 1);
		    echo '<br />';
		    HTML_joomleague::showClubIcon($guestteam, $config['show_logo_small'], 1);
		    ?></td>
		    <?php
		  }
	    ?>
	
		  <td align="left" valign="top" width="30%" nowrap="nowrap"><?php
			  $namehighlight=(in_array($hometeam->id, $favteam)) ? 1 : 0;
			  $namebold = (isset($team_plan)&&$team_plan->id == $hometeam->id) ? 1 : 0;
			  echo HTML_joomleague::formatTeamname ($hometeam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			  echo '<br />';
			  $namehighlight=(in_array($guestteam->id, $favteam)) ? 1 : 0;
			  $namebold = (isset($team_plan)&&$team_plan->id == $guestteam->id) ? 1 : 0;
			  echo HTML_joomleague::formatTeamname ($guestteam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			  ?>
		  </td>
	  	  <?php
	  	  echo show_result_below($matchInfo, $config['show_part_results']);
	  }
	  else {
	  	// TeamA
	  	$namehighlight=(in_array($hometeam->id, $favteam)) ? 1 : 0;
      $namebold = (isset($team_plan)&&$team_plan->id == $hometeam->id) ? 1 : 0;
      
	  	$teamA_html = "";
		  if ($config['show_logo_small'] > 0) {
		    $teamA_html = '<td align="right" valign="top" nowrap="nowrap" style="width: 5%;">'
		                  .HTML_joomleague::getClubIconHtml($hometeam, $config['show_logo_small'])
									    .'</td>';
		  }
		  $teamA_html .= '<td align="left" valign="top" width="30%" nowrap="nowrap">';
		  $teamA_html .= HTML_joomleague::formatTeamname ($hometeam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			$teamA_html .= '</td>';
		  
		  $separator = '<td align="left" valign="top" width="5%" nowrap="nowrap">-</td>';

		  //Team B
      $namehighlight=(in_array($guestteam->id, $favteam)) ? 1 : 0;
      $namebold = (isset($team_plan)&&$team_plan->id == $guestteam->id) ? 1 : 0;
      
      $teamB_html = "";
      if ($config['show_logo_small'] > 0) {
        $teamB_html = '<td align="right" valign="top" nowrap="nowrap" style="width: 5%;">'
                      .HTML_joomleague::getClubIconHtml($guestteam, $config['show_logo_small'])
                      .'</td>';
      }
      $teamB_html .= '<td align="left" valign="top" width="30%" nowrap="nowrap">';
      $teamB_html .= HTML_joomleague::formatTeamname ($guestteam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
      $teamB_html .= '</td>';
      
      $score_html = '<td align="right" valign="top" nowrap="nowrap">'
                    .show_result($matchInfo, $config['show_part_results'])
                    .'</td>';
                    
      switch ($config['result_style']) {
      	case 0 :
          echo $teamA_html.$separator.$teamB_html.$score_html;
          break;
        case 1 :
          echo $teamA_html.$score_html.$teamB_html.'<td>&nbsp;</td>';
          break;
      }
		}
	  ?>
	  <td align="center" valign="top" nowrap="nowrap"><?php
		  if($matchInfo->show_report == 1) {
		    echo HTML_joomleague::show_report_icon($matchInfo->match_id);
		  }
		  ?>
	  </td>
	  <?php
	  if ( $config['show_referee']) {
	    ?>
	    <td align="right" valign="top" nowrap="nowrap"><?php
		    if (!is_null($matchInfo->referee_id) and $matchInfo->referee_id>0) {
		      //echo HTML_joomleague::show_referee($matchInfo->referee_id, $joomleague->teams_as_referees);
		      if ($joomleague->teams_as_referees) echo $matchInfo->referee_name;
		      else echo $matchInfo->referee_lastname.", ".$matchInfo->referee_firstname;
		    } ?>
	    </td>
	    <?php
	  }
	  $matchInfo->home = $hometeam->name;
	  $matchInfo->away = $guestteam->name;
	  if ($joomleague->enable_sb && $config['show_fireboard_link']) {
		  ?>
			  <td align="right" valign="top" nowrap="nowrap"><?php echo HTML_joomleague::make_forumlink($matchInfo);?>
			  </td>
		  </tr>
		  <?php
    }
	  if ($config['show_events']==1 && ($are_there_events > 0 || $matchInfo->match_result_detail!="")) {
	    HTML_joomleague::show_events_container_in_results($matchInfo, 'none', $config);
	  }
	}
	
	function show_result(&$match, $show_part_results=0) {
	  global $joomleague;
	  $matchresulttype=array('', _JL_RESULTS_OVERTIME, _JL_RESULTS_PENALTY);
	  $goalshome = (is_null($match->matchpart1_result)) ? "-" : $match->matchpart1_result;
	 	$goalsaway = (is_null($match->matchpart2_result)) ? "-" : $match->matchpart2_result;
	 	$mrt = $matchresulttype[$match->match_result_type];
	  if ($match->alt_decision == 1) {
	    $mrt = '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/court.gif" border="0" alt="'.$match->decision_info.'" title="'.$match->decision_info
	    .'" border="0" />';
	    $goalshome = (isset($match->matchpart1_result_decision)) ? $match->matchpart1_result_decision : 'X';
	    $goalsaway = (isset($match->matchpart2_result_decision)) ? $match->matchpart2_result_decision : 'X';
	  }
	  $result = $goalshome.'</td><td valign="top" width="1px">:</td><td align="left" valign="top" nowrap>'.$goalsaway;
	  
	  if ($joomleague->use_legs==1) $result .= " (".$match->matchpart1_legs.":".$match->matchpart2_legs.")";
	  
	  if ($show_part_results == 1 && !is_null($match->matchpart1_result_split) && str_replace(';', '', $match->matchpart1_result_split) != '') {
	    $homepartresults=explode(";", $match->matchpart1_result_split);
	    $guestpartresults=explode(";", $match->matchpart2_result_split);
	    $result .= " (";
	    for ($x=0;$x < ($joomleague->game_parts);$x++) {
	      if (isset($homepartresults[$x]) && isset($guestpartresults[$x]) &&
	      $homepartresults[$x]!='' && $guestpartresults[$x]!='') {
	        if ($x!=0) $result .= "-";
	        $result .= $homepartresults[$x].":".$guestpartresults[$x];
	      }
	    }
	    $result .= ")";
	  }
	  $result .= ' '.$mrt;
	  return $result;
	}
	
  function show_result_below(&$match, $show_part_results=0) 
  {
    global $joomleague;
	  $matchresulttype=array('', _JL_RESULTS_OVERTIME, _JL_RESULTS_PENALTY);
    $mrt = $matchresulttype[$match->match_result_type];
	  
	  //formating score
    if ($match->alt_decision == 1) 
    {
	    $mrt = '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/court.gif" border="0" alt="'.$match->decision_info.'" title="'.$match->decision_info
	    .'" border="0" />';
	    $scorehome = (isset($match->matchpart1_result_decision)) ? $match->matchpart1_result_decision : 'X';
	    $scoreaway = (isset($match->matchpart2_result_decision)) ? $match->matchpart2_result_decision : 'X';
    }
    else
    {
      if ( !is_null( $match->matchpart1_result_split ) && ereg("[0-9]+", $match->matchpart1_result_split) )
      {
        $periodscore = explode( ';', $match->matchpart1_result_split );
        foreach ($periodscore as $score)
        {          
          if ( ereg( "([0-9]+)\.([0-9])+", $score, $res ) ) 
          {
            $homegoals += $res[1];
            $homebehinds += $res[2];
          }
        }
        $periodscore = explode( ';', $match->matchpart2_result_split );
        foreach ($periodscore as $score)
        {
          if ( ereg( "([0-9]+)\.([0-9])+", $score, $res ) ) 
          {
            $awaygoals += $res[1];
            $awaybehinds += $res[2];
          }
        }
        // display autralian football style score
        $scorehome = $homegoals.'.'.$homebehinds
                  .' ('.($homegoals*6+$homebehinds).')';
        $scoreaway = $awaygoals.'.'.$awaybehinds
                  .' ('.($awaygoals*6+$awaybehinds).')';
      }
      else if ( !is_null( $match->matchpart1_result ) )
      {
        $scorehome = $match->matchpart1_result;
        $scoreaway = $match->matchpart2_result;
      }
      else if ( is_null( $match->matchpart1_result ) )
      {
        // game not played yet
        $scorehome = "--";
        $scoreaway = "--";
      } 
    }
	  
	  $result = '';
	  if ($show_part_results == 1)
    {
	    $homepartresults=explode(";", $match->matchpart1_result_split);
	    $guestpartresults=explode(";", $match->matchpart2_result_split);
	    //$result .= " (";
	    $goals_home = 0;
	    $behinds_home = 0;
	    $goals_away = 0;
	    $behinds_away = 0;
	    $partScoreSum_home = 0;
	    $partScoreSum_guest = 0;
	    for ( $x=0;$x < ($joomleague->game_parts);$x++ ) 
      {
	      if ( isset($homepartresults[$x]) && isset($guestpartresults[$x] ) &&
	           $homepartresults[$x]!='' && $guestpartresults[$x]!='' ) 
        {
	        // if ($x!=0) $result .= "-";
	        $partScoreSum_home += (float) $homepartresults[$x];
	        $partScoreSum_guest += (float) $guestpartresults[$x];
	        if ( ereg( "([0-9]+)\.([0-9])+", $homepartresults[$x], $res ) ) 
          {
            $goals_home += $res[1];
            $behinds_home += $res[2];
          }
	        if ( ereg( "([0-9]+)\.([0-9])+", $guestpartresults[$x], $res ) ) 
          {
            $goals_away += $res[1];
            $behinds_away += $res[2];
          }
	        $result .= '<td style="text-align:right">'.$goals_home.'.'.$behinds_home.'<br />'.$goals_away.'.'.$behinds_away.'</td>';
	      }
	      else $result .= '<td style="text-align:right">--<br />--</td>';
	    }
	  }
	  
	  if ($joomleague->allow_add_time == 1 && $mrt!='') 
    {
	    $OTScore_home = $match->matchpart1_result_ot;
	    $OTScore_guest = $match->matchpart2_result_ot;
	    $result .= '<td style="text-align:right">'.$OTScore_home.'<br />'.$OTScore_guest.'</td>';
	  }
	  else if ($joomleague->allow_add_time == 1) {
      $result .= '<td style="text-align:right">&nbsp;</td>';
    }
	  
	  $result .= '<td style="text-align:right"><b>'.$scorehome.'<br />'.$scoreaway.'</b></td>';
	  if ($joomleague->allow_add_time == 1) $result.= '<td style="text-align:right">&nbsp;</td>';	  
    if ($joomleague->use_legs==1) $result .= '<td style="text-align:right">'.$match->matchpart1_legs.'<br />'.$match->matchpart2_legs.'</td>';
	  
	  $result .= '<td>'.$mrt.'</td>';
    return $result;
	}
  
?>

<a name="jl_top" id="jl_top"></a>
<!-- Header with Project Name-->
<?php if ($results_config['show_project_heading'] > 0 OR $overall_config['show_project_heading'] > 0) { ?>
<div class="componentheading" <?php if ($results_config['show_print_button'] == "1" OR $overall_config['show_print_button'] == "1") echo 'style="float:left;"';?>><?php echo HTML_joomleague::showTitle($joomleague, $overall_config['project_heading_type']); ?></div>
<!-- Druckfunktion -->
<?php if ($results_config['show_print_button'] == "1" OR $overall_config['show_print_button'] == "1") {
HTML_joomleague::PrintIcon( $row, $params, false, '' );
};?>
<!-- Druckfunktion Ende -->
<?php } ?>
<!-- Header END -->

<!-- section header e.g. ranking, results etc. -->

<table width="100%" class="contentpaneopen">
	<tr>
		<td class="contentheading">
<?php 
if ($current_round>0) {
  if ($results_config['show_section_heading']==1) {
    $title = _JL_RESULTS;
    if (isset($division)) $title .= ' '.$division->name;
    //1 request for current round
    HTML_joomleague::show_matchdays_title($title, $rounds[$current_round-1]->id, $results_config);
	  if (defined('JL_SHOW_EDIT_ICON')) HTML_joomleague::show_edit_icon($current_round, $jl_func);
	}
}

else {
	//1 request for current round
	if ($results_config['show_section_heading']==1) HTML_joomleague::show_matchdays_title(_JL_PLAN." - ". $team->name, 0, $results_config);
}
	?>
    </td>
<?php 

// select navigation of matchdays for browsing mode START
if (isset($pageNav2)&&$results_config['show_matchday_dropdown']==1) echo '<td align="right">'._JL_MATCHDAYS_SELECT.$pageNav2.'</td>';
// select navigation of matchdays for browsing mode ENDS    
?>
  </tr>

</table>
<br />

<!-- Main START -->
<div id="jlg_ranking_table">
<table width="96%" align="center" border="0" cellpadding="3" cellspacing="0">
	<?php
		if ( isset($overall_config['results_below'])&&$overall_config['results_below']==1) 
		  $results_config['results_below']=1;
		
		HTML_joomleague::resultsColspan($results_config);
		
		if (count($matches) > 0) {
		  show_matches($matches, $resultTeams, $results_config);
		}
	?>
</table>
</div>
<!-- Main END -->

<!-- Matchdays Output  -->
<?php if (isset($pageNav)&&$results_config['show_matchday_pagenav']==1) { ?>

<table width="96%" align="center" border="0" cellpadding="3" cellspacing="0">
  <tr>
   <td align="center"><br /><?php echo $pageNav ?></td>
  </tr>
</table>
<?php };?>
<!-- Matchdays Output END --> 

<!-- Print Button START -->
<?php if ($results_config['show_back_button'] > 0 OR $overall_config['show_back_button'] > 0) {;?>
<?php if ($results_config['show_back_button'] == "1" OR $overall_config['show_back_button'] == "1") echo '<div align="left">'; else echo '<div align="right">';?>
<?php
$params = & new mosParameters( '' );
$params->def( 'back_button', true );
$params->def( 'popup', false );
mosHTML::BackButton( $params );
?></div> 
<?php };?>
<!-- Print Button END -->
